package com.heiyu.utils;

import java.io.*;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;

public class FileUtils {

    public static String upload(MultipartFile file) {
        // endpoint以杭州为例，其它region请按实际情况填写
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建
        String accessKeyId = "UGJAdOzG2k9uAgIc";
        String accessKeySecret = "PF4lOWWlvIkOckiQviz4GpviZ5tkS8";
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上传
        byte[] content = null;
        try {
            content = file.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String fileName = StringUtils.lowerCase(file.getOriginalFilename());
        String[] fileNameArray = StringUtils.split(fileName, ".");
        fileName = System.currentTimeMillis() + "" + RandomStringUtils.random(3, false, true) + "." + fileNameArray[fileNameArray.length - 1];
        ossClient.putObject("dafenqi", fileName, new ByteArrayInputStream(content));
        // 关闭client
        ossClient.shutdown();
        return "https://dafenqi.oss-cn-hangzhou.aliyuncs.com/"+fileName;
    }

    public static String read(String path){
        File file = new File(path);
        if(file.exists()){
            try {
                FileInputStream fis = new FileInputStream(file);
                byte[] bytes = new byte[fis.available()];
                fis.read(bytes);
                return new String(bytes);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            return null;
        }
        return null;
    }

}
